#ifndef __TEMPLATE_2D_MALLOC_H__
#define __TEMPLATE_2D_MALLOC_H__

template <class T> 
T **template2DMalloc(size_t m, size_t n) {
    size_t total_size = sizeof(T *) * m + m * n * sizeof(T);
    char *orig_ptr = (char *)malloc(total_size);
    T *buf_ptr = orig_ptr + sizeof(T *) * m;
    T **ptr_ptr = (T **)orig_ptr;
    size_t i;
    for (i = 0; i < m; i++) {
        ptr_ptr[i] = buf_ptr + i * n * sizeof(T);
    }

    return ptr_ptr;
}

template <class T>
void template2DFree(T **ptr) {
    if (ptr == NULL) {
        return;
    }

    free((void *)ptr);
    return;
}

#endif

